package org.angelica.aliyun.manager;

import com.aliyun.opensearch.OpenSearchClient;
import com.aliyun.opensearch.SearcherClient;
import com.aliyun.opensearch.SuggestionClient;
import com.aliyun.opensearch.sdk.dependencies.com.google.common.collect.Lists;
import com.aliyun.opensearch.sdk.dependencies.org.apache.commons.lang.StringUtils;
import com.aliyun.opensearch.sdk.dependencies.org.json.JSONArray;
import com.aliyun.opensearch.sdk.dependencies.org.json.JSONObject;
import com.aliyun.opensearch.sdk.generated.OpenSearch;
import com.aliyun.opensearch.sdk.generated.commons.OpenSearchClientException;
import com.aliyun.opensearch.sdk.generated.commons.OpenSearchException;
import com.aliyun.opensearch.sdk.generated.search.Config;
import com.aliyun.opensearch.sdk.generated.search.SearchFormat;
import com.aliyun.opensearch.sdk.generated.search.SearchParams;
import com.aliyun.opensearch.sdk.generated.search.Sort;
import com.aliyun.opensearch.sdk.generated.search.general.SearchResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * 开放搜索服务
 * @author aizhimin
 */
public class OpenSearchManager {
    private static final Logger logger = LoggerFactory.getLogger(OpenSearchManager.class);

    private static final String STATUS_OK = "OK";

    private OpenSearchClient openSearchClient;
    private String appname;
    private String suggestionName;

    public OpenSearchManager(String accessKeyId,String accessKeySecret,String host,String appname,String suggestionName){
        OpenSearch openSearch = new OpenSearch(accessKeyId, accessKeySecret, host);
        openSearchClient = new OpenSearchClient(openSearch);
        this.appname = appname;
        this.suggestionName = suggestionName;
    }

    /**
     * 搜索文档
     * @param query
     * @param filter
     * @param sorter
     * @param pageNo
     * @param pageSize
     * @param fetchFields
     * @return
     * @throws OpenSearchClientException
     * @throws OpenSearchException
     */
    public String searchDoc(String query, String filter, Sort sorter, int pageNo, int pageSize, List<String> fetchFields) throws OpenSearchClientException, OpenSearchException {
        //创建SearcherClient对象，并以OpenSearchClient对象作为构造参数
        SearcherClient searcherClient = new SearcherClient(openSearchClient);
        //定义Config对象，用于设定config子句参数，分页或数据返回格式，指定应用名等等
        Config config = new Config(Lists.newArrayList(appname));
        config.setStart((pageNo - 1) * pageSize);
        config.setHits(pageSize);
        //设置返回格式为FULLJSON，目前支持返回 XML，JSON，FULLJSON 等格式
        config.setSearchFormat(SearchFormat.FULLJSON);
        // 设置搜索结果返回应用中哪些字段
        if (fetchFields != null && !fetchFields.isEmpty()) {
            config.setFetchFields(fetchFields);
        }
        // 创建参数对象
        SearchParams searchParams = new SearchParams(config);
        if (StringUtils.isNotBlank(query)) {
            searchParams.setQuery(query);
        }
        if (StringUtils.isNotBlank(filter)) {
            searchParams.setFilter(filter);
        }
        if (sorter != null) {
            searchParams.setSort(sorter);
        }

        // 执行返回查询结果
        SearchResult searchResult = searcherClient.execute(searchParams);
        String resultStr = searchResult.getResult();
        if (StringUtils.isNotBlank(resultStr)) {
            JSONObject resultJson = new JSONObject(resultStr);
            String status = resultJson.getString("status");
            if (status != null && STATUS_OK.equals(status)) {
                return resultStr;
            }
        }
        return null;
    }

    /**
     * 搜索提示
     * @param query
     * @return
     * @throws OpenSearchClientException
     * @throws OpenSearchException
     */
    public List<String> suggestDoc(String query) throws OpenSearchClientException, OpenSearchException {
        List<String> suggestList = Lists.newArrayList();
        SuggestionClient suggestionClient = new SuggestionClient(suggestionName, openSearchClient);
        suggestionClient.setQuery(query);
        suggestionClient.setHits((byte)6);
        String result = suggestionClient.search();
        if(StringUtils.isNotBlank(result)){
            JSONObject resultJson = new JSONObject(result);
            JSONArray resultJsonArray = resultJson.getJSONArray("suggestions");
            for(int i=0;i<resultJsonArray.length();i++){
                suggestList.add(resultJsonArray.getJSONObject(i).getString("suggestion"));
            }
        }
        return suggestList;
    }
}
